require('./page.css');
require('configModule');
let cp = require('cp');
let md5 = require('js-md5');
let Base64 = require('js-base64').Base64;
let vm_register = avalon.define({
  $id: 'mc_register',
  mobile: '',
  getCodeText: '点击获取',
  disableClass: '',
  time: '',
  code: '',
  password: '',
  bindGetCode: function(disable) {
    if (disable !== 'disable') {
      if (vm_register.mobile === '') {
        cp.layerMsg({msg: '请填写手机号！'});
      } else {
        let reg = (/^1[3|4|5|7|8][0-9]{9}$/).test(vm_register.mobile);
        if (reg) {
          cp.ajaxUrl({
            controller: 'account',
            cmd: 'com.rel.porg.pb.acc_send_verfiy_code_req',
            data: {mobile: vm_register.mobile, module: 1},
            checkUser: false,
            success: function(res) {
              getTime(120);
            },
            fail: res => {
              cp.layerMsg({
                msg: res.desc,
              });
            },
          });
        } else {
          cp.layerMsg({msg: '请填写正确的手机号！'});
        }
      };
    }
  },
  validate: {
    onValidateAll: function(reasons) {
      if (reasons.length) {
        cp.layerMsg({msg: reasons[0].getMessage()});
      } else {
        cp.ajaxUrl({
          cmd: 'com.rel.porg.pb.acc_sign_up_req',
          controller: 'account',
          checkUser: false,
          data: {
            mobile: vm_register.mobile,
            passwd: Base64.encode(md5(vm_register.password).toUpperCase()),
            vcode: vm_register.code,
          },
          success: function(res) {
            cp.setCookie('token', res.token, 12);
            const libs = require('libs');
            libs.sendParamBetweenPages('common', 'orgid', res.info.orgid);
            if (res.token) {
              window.location.href = cp.PAGE_ROOT + 'index/index/page.html';
            }
          },
          fail: (res) => {
            cp.layerMsg({
              msg: res.desc,
            });
          },
        });
      }
    },
  },
});

function getTime(time) {
  // 倒计时60s
  if (time === 1) {
    vm_register.getCodeText = '点击获取';
    vm_register.disableClass = '';
    vm_register.time = '';
    time = 120;
  } else {
    time--;
    vm_register.time = time;
    setTimeout(function() {
      getTime(time);
    }, 1000);
    vm_register.getCodeText = '重新获取';
    vm_register.disableClass = 'disable';
  }
}
